package cn.xuan.scan.service.impl.realm;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import cn.xuan.pojo.SysPermissions;
import cn.xuan.pojo.SysRoles;
import cn.xuan.pojo.SysUsers;
import cn.xuan.scan.service.Userservice;

public class UserRealm extends AuthorizingRealm {
	private static final Logger logger = LoggerFactory.getLogger(UserRealm.class);

	@Autowired
	private Userservice userservice;

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		logger.info("UserRealm.doGetAuthorizationInfo.PrincipalCollection");

		String username = (String) principals.getPrimaryPrincipal();

		List<SysRoles> roles = new ArrayList<>();
		List<SysPermissions> permissions = new ArrayList<>();
		try {
			roles = userservice.findRoles(username);
			permissions = userservice.findPermissions(username);
		} catch (Exception e) {
			logger.error("UserRealm.doGetAuthorizationInfo", e);
		}

		Set<String> stRoles = new HashSet<String>();
		Set<String> stPermissions = new HashSet<String>();

		for (SysRoles r : roles) {
			stRoles.add(r.getRole());
		}

		for (SysPermissions p : permissions) {
			stPermissions.add(p.getPermission());
		}

		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		authorizationInfo.setRoles(stRoles);
		authorizationInfo.setStringPermissions(stPermissions);

		return authorizationInfo;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		logger.info("UserRealm.doGetAuthorizationInfo.AuthenticationToken");
		String username = (String) token.getPrincipal();

		SysUsers user = null;
		try {
			user = userservice.findByUsername(username);
		} catch (Exception e) {
			logger.error("UserRealm.doGetAuthorizationInfo", e);
		}

		if (user == null) {
			throw new UnknownAccountException();// 没找到帐号
		}

		if (Boolean.TRUE.equals(user.getLocked())) {
			throw new LockedAccountException(); // 帐号锁定
		}

		// 交给AuthenticatingRealm使用CredentialsMatcher进行密码匹配，如果觉得人家的不好可以自定义实现
		SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user.getUsername(), // 用户名
				user.getPassword(), getName() // realm name
		);
		return authenticationInfo;
	}

}
